package com.platform.security.mybatis;

import com.platform.common.logger.annotation.EnableLogger;
import com.platform.domain.model.Role;
import com.platform.domain.model.User;
import com.platform.security.model.UserInfo;
import com.platform.service.RoleService;
import com.platform.service.UserService;
import org.apache.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class PlatformUserDetailService implements UserDetailsService {

    @EnableLogger
    private static Logger logger;

    private UserService userService;

    private RoleService roleService;

    public PlatformUserDetailService(UserService userService, RoleService roleService) {
        this.userService = userService;
        this.roleService = roleService;
    }

    /**
     * 用户登录验证
     *
     * @param loginId 登录ID
     * @return 用户详细信息
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String loginId) throws UsernameNotFoundException {
        try {
            if (loginId != null && loginId.length() > 0) {
                User user = userService.selectByLoginId(loginId);
                if (user != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("用户名：[" + user.getName() + "] 机构：+[" + user.getDeptId() + "]");
                    }
                    Collection<GrantedAuthority> grantedAuths = getGrantedAuthorities(user);
                    boolean enables = true;
                    boolean accountNonExpired = true;
                    boolean credentialsNonExpired = true;
                    boolean accountNonLocked = true;
                    // 封装成spring security的user
                    UserInfo userdetail = new UserInfo(user.getLoginId(), user.getPassword(), enables, accountNonExpired, credentialsNonExpired, accountNonLocked, grantedAuths);
                    userdetail.setUser(user);
                    return userdetail;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据用户ID查询用户权限集合
     *
     * @param user 用户对象
     * @return 权限集合
     */
    private Set<GrantedAuthority> getGrantedAuthorities(User user) {
        try {
            List<Role> userRoles = roleService.selectByUserId(user.getUserId());
            if (userRoles != null) {
                Set<GrantedAuthority> authSet = new HashSet<GrantedAuthority>();
                for (Role userRole : userRoles) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("用户：[" + user.getLoginId() + "]拥有角色：[" + userRole.getRoleName() + "],即spring security中的access");
                    }
                    authSet.add(new SimpleGrantedAuthority(userRole.getRoleId()));
                }
                return authSet;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
